package com.itbaizhan.shopping_goods_service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itbaizhan.shopping_common.pojo.Brand;
import com.itbaizhan.shopping_common.result.BusException;
import com.itbaizhan.shopping_common.result.CodeEnum;
import com.itbaizhan.shopping_common.service.BrandService;
import com.itbaizhan.shopping_goods_service.mapper.BrandMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@DubboService
@Transactional
@Service
public class BrandServiceImpl implements BrandService {
	
	@Autowired
	private BrandMapper brandMapper;
	
	/**
	 * 根据id查询品牌
	 *
	 * @param id
	 * @return
	 */
	public Brand findById(Long id) {
//		if (id == 0) {
//			int i = 1 / 0;
//		} else if (id == 1) {
//			throw new BusException(CodeEnum.PARAMETER_ERROR);
//		}
		return brandMapper.selectById(id);
	}
	
	/**
	 * 查询所有品牌
	 *
	 * @return
	 */
	public List<Brand> findAll() {
		return brandMapper.selectList(null);
	}
	
	/**
	 * 添加品牌
	 *
	 * @param brand
	 */
	public void add(Brand brand) {
		brandMapper.insert(brand);
	}
	
	/**
	 * 修改品牌
	 *
	 * @param brand
	 */
	public void update(Brand brand) {
		brandMapper.updateById(brand);
	}
	
	/**
	 * 删除品牌
	 *
	 * @param id
	 */
	public void delete(Long id) {
		brandMapper.deleteById(id);
	}
	
	/**
	 * 分页查询品牌，模糊查询
	 *
	 * @param brand
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<Brand> search(Brand brand, int page, int size) {
		QueryWrapper<Brand> wrapper = new QueryWrapper<>();
		
		if (brand != null && StringUtils.hasText(brand.getName())) {
			if (brand.getName() != null && !brand.getName().equals("")) {
				wrapper.like("name", brand.getName());
			}
		}
		
		Page<Brand> pageBrand = brandMapper.selectPage(new Page<>(page, size), wrapper);
		return pageBrand;
	}
}
